import { _decorator, CCFloat, Color, Component, EditBox, EventTouch, find, Input, input, instantiate, Label, Node, Prefab, v2, v3, Vec2 } from 'cc';
import WorldManager from './WorldManager';
import MapApi from '../api/MapApi';
import VillageApi from '../api/VillageApi';
import { UserInfo } from './UserInfo';
import { UIManager } from './UIManager';
import { EventManager } from '../event/EventManager';
import { VillageInformation } from '../world/VillageInformation';
import { PrefabEnum } from './PrefabEnum';

import ResManager from './ResManager';
import { LineGraphics } from './LineGraphics';
import { Army, ArmyState } from '../entity/Army';
import { MapZone } from '../entity/MapZone';
import { TilesManager } from './TilesManager';
import { March } from '../animal/March';
import { Plane } from '../world/Plane';
import { Hero } from '../animal/Hero';
import { WorldCamera } from './WorldCamera';
import { AudioManager, Mp3Enum } from './AudioManager';




const { ccclass, property } = _decorator;

@ccclass('WorldController')
export class WorldController extends Component {

    public static instance: WorldController;
    /**预先设置世界地图的中心，一进入世界地图，便以这个点为中心 */
    public static centerPos: Vec2
    @property(Label)
    curCoord: Label

    public stage: Node;
    private goBtn: Node
    private xInput: EditBox;
    private yInput: EditBox;

    private curArrow: Node

    /**地图上的虚线 */
    dashedList: Node[] = []
    /**地图上的行军 */
    marchList: Node[] = []

    protected onLoad(): void {
        WorldController.instance = this;
    }


    start() {
       
        this.stage = find('Canvas/Stage')
        this.goBtn = find('Canvas/UIRoot/goZoneBg/white-btn')
        this.xInput = find('Canvas/UIRoot/goZoneBg/input-x').getComponent(EditBox)
        this.yInput = find('Canvas/UIRoot/goZoneBg/input-y').getComponent(EditBox)

        this.goBtn.on(Node.EventType.TOUCH_END, this.goBtnHand, this)

        EventManager.instance.on(EventManager.EventType.GetVillageDetail, this.init, this)

        AudioManager.instance.playClip(Mp3Enum.world_0)
    }

    update() {
        let cameraPos = WorldCamera.instance.node.position

        let a = WorldManager.instance.convertCoord(cameraPos)
        let xy = v2(a.x / WorldManager.instance.sizeX, a.y / WorldManager.instance.sizeY)
        let x = xy.x.toFixed()
        let y = xy.y.toFixed()
        this.curCoord.string = `当前坐标：X : ${x}     Y : ${y}`
    }

    async init() {
        if(!this.enabled){
            return
        }
        try {
            UIManager.instance.showLoading()
            await TilesManager.getTilesConfig()
            UIManager.instance.closeLoading()
        } catch (error) {
            
        }
       
        if (WorldController.centerPos) {
            this.goZone(WorldController.centerPos.x, WorldController.centerPos.y)
            WorldController.centerPos = null
        } else {
            //获取自己村周边的地图数据
            this.goHome()
        }
        // 显示行军路线
        this.showArmyLine()




        // 创建英雄
        // Hero.createHeroByXY(UserInfo.instance.villageData.xId, UserInfo.instance.villageData.yId)
    }

    async setCurArrow() {
        let canvas = find('Canvas')
        for (let item of canvas.children) {
            if (item.name == 'spaceTip') {
                item.destroy()
            }
        }

        let children = WorldController.instance.stage.children
        for (let ch of children) {
            let zone = ch.getComponent(Plane).zone

            if (!zone) {
                continue
            }
            if (zone.zoneId == UserInfo.instance.villageData.curVid) {
                let prefab = await ResManager.instance.loadAssetByUrl<Prefab>('village/spaceTip')
                let node = instantiate(prefab)
                canvas.addChild(node)

                node.worldPosition = ch.worldPosition
                node.scale = v3(0.5, 0.5, 0.5)
                node.translate(v3(0, 80, 0))
            }

            if (zone.uid == UserInfo.instance.villageData.uid) {
                let prefab = await ResManager.instance.loadAssetByUrl<Prefab>('village/spaceTip')
                let node = instantiate(prefab)
                canvas.addChild(node)

                node.worldPosition = ch.worldPosition
                node.scale = v3(0.3, 0.3, 0.3)
                node.translate(v3(0, 80, 0))
            }
        }
    }

    async refresh() {
        WorldController.instance.stage.destroyAllChildren()
        // await this.goHome()
        UserInfo.instance.refreshVillageDetail()
    }

    async goHome() {

        await UIManager.instance.showLoading()
        let res = await MapApi.goHome({ size: 7 })
        await UIManager.instance.closeLoading()
        let data = res.data
        console.info('goHome:', res)
        await WorldManager.instance.createPartMap(data)


        this.setCurArrow()
        return data
    }
    async goZone(x: number, y: number, setCameraPos: boolean = true) {

        let res = await MapApi.goZone({ x, y, size: 7 })
        UIManager.instance.closeLoading()
        let data = res.data
        console.info('goZone:', res)
        await WorldManager.instance.createPartMap(data, setCameraPos)

        this.setCurArrow()
        return data
    }

    goBtnHand() {
        let x = this.xInput.string
        let y = this.yInput.string
        if (!/\d+/.test(x)) {
            UIManager.instance.tip('请输入数字')
            return
        }
        if (!/\d+/.test(y)) {
            UIManager.instance.tip('请输入数字')
            return
        }
        let xNum = parseInt(x)
        let yNum = parseInt(y)
        if (xNum < -400 || xNum > 400) {
            UIManager.instance.tip('请输入数字-400 ~ 400')
            return
        }
        if (yNum < -400 || yNum > 400) {
            UIManager.instance.tip('请输入数字-400 ~ 400')
            return
        }

        this.goZone(xNum, yNum)
    }

    // async onPlaneClick(zone) {
    //     await UIManager.instance.showLoading()
    //     let ui = await UIManager.instance.openUI(PrefabEnum.VillageInformation)
    //     UIManager.instance.closeLoading()
    //     ui.getComponent(VillageInformation).setData(zone)

    // }

    /**显示行军路线 */
    async showArmyLine() {
        console.log('showArmyLine...')
        for (let dashed of this.dashedList) {
            dashed.destroy()
        }
        this.dashedList = []

        for (let m of this.marchList) {
            m.destroy()
        }
        this.marchList = []


        for (let item of UserInfo.instance.soldiersInNotArrivedList) {
            let army = Army.createArmyByData(item)
            let xy = MapZone.getXyByZoneId(army.zoneId, WorldManager.instance.radius)
            let start = WorldManager.instance.getWorldPostionByXY(v2(xy[0], xy[1]))
            xy = MapZone.getXyByZoneId(army.simZoneId, WorldManager.instance.radius)
            let end = WorldManager.instance.getWorldPostionByXY(v2(xy[0], xy[1]))

            let dashed = await LineGraphics.createDashed(start, end, army.endTime)
            this.dashedList.push(dashed)
            let m = await March.create(v2(start.x, start.y), v2(end.x, end.y), army.startTime, army.endTime)
            this.marchList.push(m)
        }

        for (let item of UserInfo.instance.soldiersOutNotArrivedList) {
            let army = Army.createArmyByData(item)
            let xy = MapZone.getXyByZoneId(army.zoneId, WorldManager.instance.radius)
            let start = WorldManager.instance.getWorldPostionByXY(v2(xy[0], xy[1]))
            xy = MapZone.getXyByZoneId(army.simZoneId, WorldManager.instance.radius)
            let end = WorldManager.instance.getWorldPostionByXY(v2(xy[0], xy[1]))

            if (army.state == ArmyState.Back) {
                let dashed = await LineGraphics.createDashed(end, start, army.endTime, new Color('#25AC03'))
                this.dashedList.push(dashed)
                let m = await March.create(v2(end.x, end.y), v2(start.x, start.y), army.startTime, army.endTime)
                this.marchList.push(m)
            } else {
                let dashed = await LineGraphics.createDashed(start, end, army.endTime)
                this.dashedList.push(dashed)
                let m = await March.create(v2(start.x, start.y), v2(end.x, end.y), army.startTime, army.endTime)
                this.marchList.push(m)
            }

        }



    }

}


